# -*- coding: utf-8 -*-

# Copyright 2011 Google Inc. All Rights Reserved.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from google.appengine.dist import use_library
use_library('django', '1.2')

import cgi
import datetime
import logging
import os

from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import login_required

import model

class ListGuestDataHandler(webapp.RequestHandler):

    @login_required
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        guests = model.Guest.all()
        guests.order("name")
        status = self.request.get('status')
        op = self.request.get('op')
        edit_id = self.request.get('edit_id')
        form = model.GuestForm()
        if edit_id:
            guest = model.Guest.get_by_key_name(
                edit_id, parent=model.main_event)
            form = model.GuestForm(instance=guest)
        message = ""
        if op == 'add' or op == 'edit':
            if status == 'ok':
                op_msg = 'edited'
                if op == 'add':
                    op_msg = 'added'
                message = 'Guest %s %s succesfully' % (
                    self.request.get('name'), op_msg)
            elif status == 'error':
                message = ('Some errors were found, please review it and'
                           'try again')
                form = model.GuestForm(data=self.request.GET)
        if op == 'mail':
            if status == 'ok':
                message = 'Mail to %s sent succesfully' % (
                    self.request.get('name'))
            elif status == 'error':
                message = 'Failed to send mail to %s, try again later' % (
                    self.request.get('name'))
        if op == 'delete' and status == 'ok':
                message = 'Guest %s deleted succesfully' % (
                    self.request.get('name'))
        totals = [(i.extra_guests + 1, i.rsvp == 'Yes') for i in guests]
        guest_total = sum([i[0] for i in totals])
        guest_confirmed = sum([i[0] for i in totals if i[1]]) 
        template_values = {'guests': guests,
                           'm': message,
                           'total': guest_total,
                           'confirmed': guest_confirmed,
                           'form': form,
                           'edit_id': edit_id}
        path = os.path.join(os.path.dirname(__file__), 'list.html')
        self.response.out.write(template.render(path, template_values))

class AddGuestDataHandler(webapp.RequestHandler):

    def post(self):
        status = 'error'
        name = self.request.get('name')
        email = self.request.get('email')
        edit_id = self.request.get('edit_id')
        guest = None
        op = None
        if not edit_id:
            edit_id = model.produce_hash(name, email)
            guest = model.Guest(parent=model.main_event, 
                                key_name=edit_id, name=name, email=email)
            op = 'add'
        else:
            guest = model.Guest.get_by_key_name(
                edit_id, parent=model.main_event)
            op = 'edit'
        form = model.GuestForm(data=self.request.POST, instance=guest)
        if form.is_valid():
            form.save(commit=False)
            guest.put()
            status = 'ok'
        self.redirect('/admin/?op=%s&status=%s&name=%s&email=%s' % (
                op, status, cgi.escape(name.encode('utf-8')),
                cgi.escape(email.encode('utf-8'))))

class MailGuest(object):

    def __init__(self, guest_id, event):
        self.event_ = event
        self.guest_id_ = guest_id
        self.name_ = ''
        self.status_ = False

    def sendmail(self):
        g = model.Guest.get_by_key_name(self.guest_id_, parent=self.event_)
        self.name_ = g.name

        message = mail.EmailMessage(
            sender=(u'Raphael Marcos Menderico e Priscilla de Fátima '
                    'Izuhara <goingtoswitzerland@menderico.com.br>'),
            subject='Você foi convidado para uma festa!')
        
        message.to = u'%s <%s>' % (g.name, g.email)
        message.bcc = 'menderico@gmail.com'
        message.reply_to = 'menderico+goingtoswitzerland@gmail.com'
        message.body = (
u"""
Olá %s,

Raphael e Priscilla pensaram bem e depois de um longo periodo de ponderação
decidiram que você (e seus convidados especiais) seriam bons convidados
para uma festa. Ainda preparamos um mega-portal onde você pode conseguir
todas as informações a respeito da festa, e um link exclusivo para ti!

Para mais informações, acesse http://rsvp.menderico.com.br/guest/%s/
""" % (g.name, g.key().name()))
        message.send()
        
        g.mail_ts = datetime.datetime.now()
        g.put()
        self.status_ = True

    def get_name(self):
        return self.name_

    def get_escaped_name(self):
        return cgi.escape(self.name_.encode('utf-8'))

    def get_status(self):
        if self.status_:
            return 'ok'
        else:
            return 'error'

class MailGuestDataHandler(webapp.RequestHandler):
    def get(self, guest_id):
        m = MailGuest(guest_id, model.main_event)
        m.sendmail()
        self.redirect('/admin/?op=mail&status=%s&name=%s' % (
                m.get_status(), m.get_escaped_name()))

class DeleteGuestDataHandler(webapp.RequestHandler):
    def get(self, guest_id):
        guest = model.Guest.get_by_key_name(
            guest_id, parent=model.main_event)
        name = guest.name
        guest.delete()
        self.redirect('/admin/?op=delete&status=ok&name=%s' % (
                cgi.escape(name.encode('utf-8'))))

def main():
    application = webapp.WSGIApplication(
        [('/admin/(.*)/delete', DeleteGuestDataHandler),
         ('/admin/(.*)/sendmail', MailGuestDataHandler),
         ('/admin/addguest', AddGuestDataHandler),
         ('/admin/.*', ListGuestDataHandler)])
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
